package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type VisualService struct {
	ak     string
	sk     string
	client *http.Client
}

func NewVisualService(ak, sk string) *VisualService {
	return &VisualService{
		ak:     "",
		sk:     "",
		client: &http.Client{},
	}
}

func (vis *VisualService) OCRPDF(filePath string) error {
	// 读取文件并编码为base64
	fileData, err := ioutil.ReadFile(filePath)

	if err != nil {
		return fmt.Errorf("read file error: %v", err)
	}
	encoded := base64.StdEncoding.EncodeToString(fileData)

	// 构建请求参数
	params := map[string]interface{}{
		"Action":        "OCRPdf",
		"Version":       "2021-08-23",
		"image_base64":  encoded,
		"version":       "v3",
		"page_start":    1,
		"page_num":      16,
		"table_mode":    "html",
		"filter_header": "true",
	}

	// 序列化请求体
	requestBody, err := json.Marshal(params)
	if err != nil {
		return fmt.Errorf("json marshal error: %v", err)
	}

	// 创建HTTP请求

	req, err := http.NewRequest("POST", "https://www.volcengine.com/api/exp/2/proxy", bytes.NewBuffer(requestBody))
	if err != nil {
		return fmt.Errorf("create request error: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s:%s", vis.ak, vis.sk))

	// 发送请求
	resp, err := vis.client.Do(req)
	if err != nil {
		return fmt.Errorf("request error: %v", err)
	}
	defer resp.Body.Close()

	// 处理响应
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("API request failed with status: %s", resp.Status)
	}

	var result struct {
		Data struct {
			Markdown string `json:"markdown"`
			Detail   string `json:"detail"`
		} `json:"data"`
	}

	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return fmt.Errorf("decode response error: %v", err)
	}

	// 保存Markdown
	if err := ioutil.WriteFile("resp.md", []byte(result.Data.Markdown), 0644); err != nil {
		return fmt.Errorf("write markdown file error: %v", err)
	}

	// 解析并保存JSON
	var jsonData interface{}
	if err := json.Unmarshal([]byte(result.Data.Detail), &jsonData); err != nil {
		return fmt.Errorf("unmarshal detail error: %v", err)
	}

	formattedJson, err := json.MarshalIndent(jsonData, "", "    ")
	if err != nil {
		return fmt.Errorf("format json error: %v", err)
	}

	if err := ioutil.WriteFile("resp.json", formattedJson, 0644); err != nil {
		return fmt.Errorf("write json file error: %v", err)
	}
	fmt.Println("OCR and save successfully. ：", formattedJson)
	return nil
}

func main() {
	vis := NewVisualService("AKLTZWU5MmUwZjhmZmIyNDRhYmI3MDg2NTE2YTE3ZDZkZmE", "WWpJeVpqRXhZemRqTVdFek5HRTNZMkZsWXpoaFlXRXdNelV4TURSaVlqUQ==")
	if err := vis.OCRPDF("D:\\ShanghaiLixiang\\topic.pdf"); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
}
